package Client;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class TrafficHandler implements Runnable {
	private Socket socket = null;
	private ObjectInputStream input = null;
	private ObjectOutputStream output = null;
	private boolean connected = false;

	//voor het gemak hardcoded
	private final static String HOST = "localhost";
	private final static Integer PORT = 64000;


	public TrafficHandler() {
		new Thread(this).start();
	}

	public void InputFromCLI(String in) {
		if(connected){
			
				try {
					output.writeObject(in);
					output.flush();
				} catch (Exception e) {					
					e.printStackTrace();
				}
						
		} else{
			if ((in.toLowerCase()).equals("open") ) {
				connected = open(HOST,PORT);
			} else{
				System.out.println("There is no connection with the server");
			}			
		}
	}

	private boolean open(String address, Integer port) {

		if (socket == null) {

			try {
				this.socket = new Socket(address, port);
				this.output = new ObjectOutputStream( socket.getOutputStream() );
				output.flush();
				this.input = new ObjectInputStream( socket.getInputStream() );
			} catch (Exception e) {
				System.out.println(e);
				return false;
			}
		}

		return true;
	}
	
	@Override
	public void run() {
		while (true) {
			try {
				Thread.sleep(50);
				String reply = (String) input.readObject();

				if ((reply.toLowerCase()).contains("close")) {
					socket.close();
					socket = null;
					output = null;
					input = null;
					connected = false;
				}
				System.out.print("> " + reply + "\n");				
			} catch (Exception e) {

			}
		}	
	}
}
